<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\Event;

use Admin\Data\Common;
use Admin\Entity\Delivery;
use Doctrine\ORM\EntityManager;
use Laminas\EventManager\Event;
use Laminas\EventManager\EventManagerInterface;
use Laminas\EventManager\ListenerAggregateInterface;
use Laminas\Mvc\I18n\Translator;
use Sales\Entity\OrderDeliveryAddress;

class LoongdomServiceListener implements ListenerAggregateInterface
{
    protected $listeners = [];

    private $translator;
    private $entityManager;

    public function __construct(
        EntityManager   $entityManager,
        Translator      $translator
    )
    {
        $this->translator = $translator;
        $this->entityManager = $entityManager;
    }

    public function attach(EventManagerInterface $events, $priority = 1)
    {
        $shareEvents = $events->getSharedManager();

        //后台订单发货完成，发送配送信息到珑大轨迹推送
        $this->listeners[] = $shareEvents->attach(
            'Sales\Controller\IndexController', 'backstage-order.ship.post', [$this, 'onSendExpressPush']
        );

        //后台订单修改快递单号，发送配送信息到珑大轨迹推送（如果在珑大服务中已经存在的则不会被添加）
        $this->listeners[] = $shareEvents->attach(
            'Sales\Controller\IndexController', 'backstage-order.editExpressNumber.post', [$this, 'onSendExpressPush']
        );
    }

    public function detach(EventManagerInterface $events)
    {
        foreach ($this->listeners as $index => $listener) {
            $events->detach($listener);
            unset($this->listeners[$index]);
        }
    }

    public function onSendExpressPush(Event $event)
    {
        $orderInfo = $event->getParam('orderInfo');
        $deliveryConfig= Common::readConfigFile('delivery');

        $deliveryApiType    = $deliveryConfig['deliveryApiType'] ?? '';
        $deliveryApiKey     = $deliveryConfig['deliveryApiKey'] ?? '';
        $orderDeliveryAddress = $this->entityManager->getRepository(OrderDeliveryAddress::class)->findOneBy(['orderId' => $orderInfo->getOrderId()]);
        if ($deliveryApiType != 'longExpressPush' || empty($deliveryApiKey) || $orderDeliveryAddress == null || $deliveryConfig['deliveryApiState'] != 1) return false;

        $expressPushMessage = [];

        if ($orderInfo->getDeliveryMode() == 2) {//单独配送
            $deliveryCodeArray  = $event->getTarget()->shopPlugin()->getExpressCodeIdArray();
            $orderGoodsList     = $orderInfo->getOrderGoods();
            foreach ($orderGoodsList as $goodsValue) {
                if ($goodsValue->getGoodsType() != 1 || $goodsValue->getDeliveryId() <= 0 || !isset($deliveryCodeArray[$goodsValue->getDeliveryId()])) return false;

                $expressPushMessage[] = [
                    'orderId'   => $orderInfo->getOrderId(),
                    'orderSn'   => $orderInfo->getOrderSn(),
                    'comName'   => $goodsValue->getDeliveryName(),
                    'comCode'   => $deliveryCodeArray[$goodsValue->getDeliveryId()],
                    'comNumber' => $goodsValue->getExpressNumber(),
                    'phone'     => $orderDeliveryAddress->getPhone()
                ];
            }
        } else {
            if (empty($orderInfo->getExpressNumber())) return false;

            $deliveryInfo = $this->entityManager->getRepository(Delivery::class)->findOneBy(['deliveryId' => $orderInfo->getDeliveryId()]);
            if ($deliveryInfo == null || empty($deliveryInfo->getDeliveryNameCode())) return false;

            $expressPushMessage[] = [
                'orderId'   => $orderInfo->getOrderId(),
                'orderSn'   => $orderInfo->getOrderSn(),
                'comName'   => $orderInfo->getDeliveryName(),
                'comCode'   => $deliveryInfo->getDeliveryNameCode(),
                'comNumber' => $orderInfo->getExpressNumber(),
                'phone'     => $orderDeliveryAddress->getPhone()
            ];
        }

        return $event->getTarget()->adminCommon()->dbshopPushService('sendOrderExpress', ['deliveryKey' => $deliveryApiKey, 'expressPushMessage' => $expressPushMessage], 'express-api');
    }
}